<template>
  <div class="data-visualization-panel">
    <div>
      <DateComponent :selected-dates="SelectedDates" @submit="handleDateSubmit" @reset="handleDateReset"/>
    </div>
    <el-row>
      <el-col :span="24">
        <el-tabs v-model="activeTab" @tab-click="handleTabChange">
          <el-tab-pane label="销量" name="sales">

          </el-tab-pane>
          <el-tab-pane label="订单数" name="orders"></el-tab-pane>
          <el-tab-pane label="退款统计" name="returns"></el-tab-pane>
          <el-tab-pane label="成交订单数" name="transactions"></el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-radio-group v-model="timeRange" @change="handleTimeChange">
          <el-radio-button label="day">日</el-radio-button>
          <el-radio-button label="week">周</el-radio-button>
          <el-radio-button label="month">月</el-radio-button>
          <el-radio-button label="year">年</el-radio-button>
        </el-radio-group>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <div ref="lineChart" class="chart"></div> <!-- 折线图 -->
      </el-col>
      <el-col :span="12">
        <div ref="barChart" class="chart"></div> <!-- 柱状图 -->
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12" v-show="false">
        <div ref="pieChart" class="chart"></div> <!-- 饼图 -->
      </el-col>
      <el-col :span="12" v-show="false">
        <div ref="funnelChart" class="chart"></div> <!-- 条状图 -->
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="date" label="日期"></el-table-column>
          <el-table-column prop="value" label="金额" v-if="activeTab==='sales'"></el-table-column>
          <el-table-column prop="value" label="订单数" v-if="activeTab==='orders'"></el-table-column>
          <el-table-column prop="value" label="退款金额" v-if="activeTab==='returns'"></el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {listDataPanel, handoffList, orderDataHandoff,orderReturnsDataHandoff,orderDealList} from "@/api/datePanel/dataPanel";
import DateComponent from './date.vue';

export default {
  components: {
    'DateComponent': DateComponent
  },
  data() {
    return {
      years: null,
      months: null,
      weeks: null,
      //当前的标签名
      activeTab: 'sales',
      //当前选择的日期
      timeRange: 'day',
      lineChart: null,//折线图数据
      barChart: null,//柱状图数据
      pieChart: null,//饼图数据
      funnelChart: null,
      tableData: [], // 用于表格的数据
      tableWeek: [],//用于表格周数据
      //选中的日期（日、周、月、年）
      SelectedDates: null,
      //选中的分类（销量，订单数，退款，成交）
      SelectedCategories: null,
      OrdersSales: [],
      lineOptionData: [],
      orderCountData: [],
      weeksData: [],//周数据
      monthData: [],//月数据
      monthPas: [],//月份
      yearData: [],//年数据
      ordersList:[],//订单数据
      returnsDataList:[],//退款数据
      orderDealDateList:[],//成交订单数据
      //销量数据
      salesData: {
        month: [],//月数据
        day: [],//日数据
        week: [],//周数据
        year: []//年数据
      },
      //订单数数据
      ordersData: {
        month: [],
        day: [],
        week: [],
        year: []
      },
      //退款数据
      returnsData: {
        day: [],
        week: [],
        month: [],
        year: []
      },
      //成交订单数
      transactionsData: {
        day: [],
        week: [],
        month: [],
        year: [],
      },
    };
  },
  //初始化数据
  mounted() {
    // if (this.SelectedCategories === "sales"){
    // 首先调用数据获取方法
    this.shuju().then(() => {
      // 数据获取成功后，初始化图表
      this.initCharts();
      // 初始化完成后，更新图表
      this.updateCharts();
    });
    // }else if (this.SelectedCategories === "orders"){
    // 首先调用数据获取方法
    // this.ordersDay().then(() => {
    //   // 数据获取成功后，初始化图表
    //   this.initCharts();
    //   // 初始化完成后，更新图表
    //   this.updateCharts();
    // });
    // }
  },
  methods: {
    //计算周数
    getWeekNumber(isoDateString) {
      let date = new Date(isoDateString);
      let firstThursday = new Date(date.getFullYear(), 0, 1 + (1 - date.getDay() + 7) % 7);
      let pastDays = (date - firstThursday) / 86400000; // 86400000 = 1000 * 60 * 60 * 24
      return Math.ceil((pastDays + 1) / 7);
    },
    // 处理DateComponent的提交事件
    handleDateSubmit(formData) {
      this.years = formData.years;
      this.months = formData.months
      this.weeks = formData.weeks;
      console.log('DateComponent提交的数据:', formData);
      console.log("选择分类的日期：", this.SelectedDates)
      console.log("选择分类的分类：", this.SelectedCategories)
      //周数赋值
      if (this.weeks != null){
        let weekNumber  = this.getWeekNumber(this.weeks);
        this.weeks = weekNumber;
      }
      //月数赋值
      if ( this.months!=null){
        let dateString = this.months;
        let month = new Date(dateString).getMonth() + 1; // getMonth() 返回的是 0-11，所以需要加1
        console.log("月份输出",month); // 输出:
        this.months = [];
        this.months = month;
      }
      if (this.SelectedDates === null && this.SelectedCategories === null && this.years ===null && this.months ===null &&  this.weeks ===null){
        this.shuju().then(() => {
          this.updateCharts();
        })
      }else if (this.SelectedDates ==="week" &&  this.SelectedCategories === null) {
        this.weeksList().then(() => {
          this.updateCharts();
        })
      }else if (this.SelectedDates ===null  && this.SelectedCategories === null || this.SelectedDates ==="day"  && this.SelectedCategories === "sales" ){
        this.shuju().then(() => {
          this.updateCharts();
        })
      }else  if (this.SelectedDates ==="month" &&  this.SelectedCategories === null || this.SelectedDates ==="month" && this.SelectedCategories === "sales"){
        console.log("month",this.months)
        this.monthList().then(() =>{
          this.updateCharts();
        })
      }else  if (this.SelectedDates ==="year" &&  this.SelectedCategories === null || this.SelectedDates ==="year" && this.SelectedCategories === "sales"){
        console.log("month",this.months)
        this.yearList().then(() =>{
          this.updateCharts();
        })
      }

    },
    // 处理DateComponent的重置事件
    handleDateReset() {
    },
    //分类
    handleTabChange(tab) {
      this.activeTab = tab.name;
      this.timeRange = "day"
      this.SelectedCategories = tab.name;
      if (this.SelectedCategories === "orders"){
        this.ordersDayList().then(()=>{
          this.updateCharts();
        })
      }
      if (this.SelectedCategories === "returns"){
        this.returnDayList().then(()=>{
          this.updateCharts();
        })
      }
      if (this.SelectedCategories === "transactions"){
        this.orderDealDayList().then(()=>{
          this.updateCharts();
        })
      }
      if (this.SelectedCategories === "sales" &&   this.SelectedDates === null ||  this.SelectedDates === "day" ){
        this.shuju().then(() => {
          this.updateCharts();
        })
      }
      console.log("选择分类的日期：", this.SelectedDates)
      console.log("选择分类的分类：", this.SelectedCategories)
    },
    //日期
    handleTimeChange(value) {
      this.SelectedDates = null;
      this.timeRange = value;
      this.SelectedDates = value;
      console.log("选择日期的日期：", this.SelectedDates)
      console.log("选择日期的分类：", this.SelectedCategories)
      if (this.timeRange === 'week' && this.activeTab === 'sales') {
        this.weeksList().then(() => {
          this.updateCharts();
        })
      } else if (this.timeRange === 'day' && this.activeTab === 'sales') {
        this.shuju().then(() => {
          this.updateCharts();
        })
      } else if (this.timeRange === 'month' && this.activeTab === 'sales') {
        this.monthList().then(() => {
          this.updateCharts();
        })
      } else if (this.timeRange === 'year' && this.activeTab === 'sales') {
        this.yearList().then(() => {
          this.updateCharts();
        })
      }
      //第一次选择订单数据
      if (this.timeRange === '' ){
        this.ordersDayList().then(()=>{
          console.log("第一次选择订单数据",this.ordersList)
          this.updateCharts();
        })
      } else  if (this.timeRange === 'day' && this.activeTab === 'orders') {
        this.ordersDayList().then(()=>{
          console.log("day",this.ordersList)
          this.updateCharts();
        })
      } else  if (this.timeRange === 'week' && this.activeTab === 'orders') {
        this.ordersWEEKSList().then(()=>{
          console.log("weeks:",this.ordersList)
          this.updateCharts();
        })
      } else  if (this.timeRange === 'month' && this.activeTab === 'orders') {
        this.ordersMonthsList().then(()=>{
          console.log("month:",this.ordersList)
          this.updateCharts();
        })
      } else  if (this.timeRange === 'year' && this.activeTab === 'orders') {
        this.ordersYearsList().then(()=>{
          console.log("year:",this.ordersList)
          this.updateCharts();
        })
      }
      if (this.timeRange === '' ){
        this.returnDayList().then(()=>{
          console.log("第一次选择订单数据",this.returnsDataList)
          this.updateCharts();
        })
      } else  if (this.timeRange === 'day' && this.activeTab === 'returns') {
        this.returnDayList().then(()=>{
          console.log("day",this.returnsDataList)
          this.updateCharts();
        })
      } else  if (this.timeRange === 'week' && this.activeTab === 'returns') {
        this.returnsWeeksList().then(()=>{
          console.log("weeks:",this.returnsDataList)
          this.updateCharts();
        })
      } else  if (this.timeRange === 'month' && this.activeTab === 'returns') {
        this.returnsMonthsList().then(()=>{
          console.log("month:",this.returnsDataList)
          this.updateCharts();
        })
      } else  if (this.timeRange === 'year' && this.activeTab === 'returns') {
        this.returnsYearsList().then(()=>{
          console.log("year:",this.returnsDataList)
          this.updateCharts();
        })
      }
      if (this.timeRange === '' ){
        this.orderDealDayList().then(()=>{
          console.log("第一次选择订单数据",this.returnsDataList)
          this.updateCharts();
        })
      } else  if (this.timeRange === 'day' && this.activeTab === 'transactions') {
        this.orderDealDayList().then(()=>{
          console.log("day",this.orderDealDateList)
          this.updateCharts();
        })
      } else  if (this.timeRange === 'week' && this.activeTab === 'transactions') {
        this.orderDealWeekList().then(()=>{
          console.log("weeks:")
          this.updateCharts();
        })
      } else  if (this.timeRange === 'month' && this.activeTab === 'transactions') {
        this.orderDealMonthList().then(()=>{
          console.log("month:")
          this.updateCharts();
        })
      } else  if (this.timeRange === 'year' && this.activeTab === 'transactions') {
        this.orderDealYearList().then(()=>{
          console.log("year:")
          this.updateCharts();
        })
      }
    },
    //初始数据
    shuju() {
      return listDataPanel(this.SelectedDates, this.SelectedCategories,this.years,this.months,this.weeks ).then(response => {
        this.OrdersSales = response.rows;
        this.salesData.day = [];
        this.lineOptionData = [];
        this.ordersData.day = [];
        this.transactionsData.day = [];
        console.log("数据", this.OrdersSales)
        for (let i = 0; i < this.OrdersSales.length; i++) {
          this.salesData.day.push(this.OrdersSales[i].orderPayPrice)
          this.lineOptionData.push(this.OrdersSales[i].orderPaymentTime)
          this.ordersData.day.push(this.OrdersSales[i].orderCount)
          this.transactionsData.day.push(this.OrdersSales[i].orderCount)
        }
        console.log("created生命周期函数", this.salesData.day)
        console.log("created生命周期函数", this.lineOptionData)
      });
    },
    //销量周数据
    weeksList() {
      if (this.timeRange === 'week' && this.activeTab === 'sales') {
        return handoffList(this.SelectedDates, this.SelectedCategories,this.years,this.months,this.weeks ).then(respnse => {
          this.weeksData = respnse.rows;
          this.salesData.week = [];
          this.ordersData.day = [];
          this.lineOptionData = [];
          this.tableWeek = [];
          for (let i = 0; i < this.weeksData.length; i++) {
            this.salesData.week.push(this.weeksData[i].orderPayPrice);
            this.tableWeek.push(this.weeksData[i].weeks);
            this.lineOptionData.push(this.weeksData[i].weeks + "周");
            this.ordersData.day.push(this.weeksData[i].OrderCount);
          }
          console.log("周数据：", this.weeksData)
        })
      } else if (this.timeRange === 'day' && this.activeTab === 'sales') {
        this.shuju();
      }
    },
    // 销量月数据
    monthList() {
      this.monthData = [];
      return handoffList(this.SelectedDates, this.SelectedCategories,this.years,this.months,this.weeks ).then(response => {
        this.monthData = response.rows;
        this.lineOptionData = [];
        this.salesData.month = [];
        this.monthPas = [];
        for (let i = 0; i < this.monthData.length; i++) {
          this.salesData.month.push(this.monthData[i].orderPayPrice);
          this.monthPas.push(this.monthData[i].months)
          this.lineOptionData.push(this.monthData[i].years + "年" + this.monthData[i].months + "月");
        }
      })
    },
    //销量年数据
    yearList() {
      this.yearData = [];
      return handoffList(this.SelectedDates, this.SelectedCategories,this.years,this.months,this.weeks ).then(response => {
        this.yearData = response.rows;
        this.lineOptionData = [];
        this.salesData.year = [];
        for (let i = 0; i < this.yearData.length; i++) {
          this.salesData.year.push(this.yearData[i].orderPayPrice)
          this.lineOptionData.push(this.yearData[i].years)
        }
      })
    },
    //订单日数据
    ordersDayList() {
      return orderDataHandoff(this.SelectedDates, this.SelectedCategories, this.years, this.months, this.weeks).then(response => {
        this.ordersData.day = [];
        this.ordersList = [];
        this.lineOptionData = [];
        this.ordersList = response.rows;
        for (let i = 0; i < this.ordersList.length; i++) {
          this.ordersData.day.push(this.ordersList[i].orderCount)
          // // 将日期时间字符串分割为日期和时间两部分，然后只取日期部分
          const dateTime = this.ordersList[i].orderCreateTime;
          const dateString = dateTime.split('T')[0]; // 只保留日期部分
          this.lineOptionData.push(dateString);
        }
      })
    },
    //  订单周数据
    ordersWEEKSList() {
      return orderDataHandoff(this.SelectedDates, this.SelectedCategories, this.years, this.months, this.weeks).then(response => {
        this.ordersData.week = [];
        this.ordersList = [];
        this.lineOptionData = [];
        this.ordersList = response.rows;
        for (let i = 0; i < this.ordersList.length; i++) {
          this.ordersData.week.push(this.ordersList[i].orderCount)
          this.lineOptionData.push(this.ordersList[i].weeks);
          this.tableWeek.push(this.lineOptionData[i]);
        }
        console.log("this.ordersList",this.ordersList)
      })
    },
    // 订单月数据
    ordersMonthsList() {
      return orderDataHandoff(this.SelectedDates, this.SelectedCategories, this.years, this.months, this.weeks).then(response => {
        this.ordersData.month = [];
        this.ordersList = [];
        this.lineOptionData = [];
        this.ordersList = response.rows;
        for (let i = 0; i < this.ordersList.length; i++) {
          this.ordersData.month.push(this.ordersList[i].orderCount)
          this.lineOptionData.push(this.ordersList[i].months);
        }
        console.log("this.ordersList",this.ordersList)
      })
    },
    // 订单年数据
    ordersYearsList() {
      return orderDataHandoff(this.SelectedDates, this.SelectedCategories, this.years, this.months, this.weeks).then(response => {
        this.ordersData.year = [];
        this.ordersList = [];
        this.lineOptionData = [];
        this.ordersList = response.rows;
        for (let i = 0; i < this.ordersList.length; i++) {
          this.ordersData.year.push(this.ordersList[i].orderCount)
          this.lineOptionData.push(this.ordersList[i].years);
        }
        console.log("this.ordersList",this.ordersList)
      })
    },
    //退款日数据
    returnDayList(){
      return orderReturnsDataHandoff(this.SelectedDates, this.SelectedCategories).then(response=>{
        this.returnsData.day = [];
        this.returnsDataList = [];
        this.lineOptionData = [];
        this.returnsDataList = response.rows;
        for (let i = 0; i < this.returnsDataList.length; i++) {
          this.returnsData.day.push(this.returnsDataList[i].returnPrice)
          this.lineOptionData.push(this.returnsDataList[i].returnApplyTime);
        }
        console.log("this.ordersList",this.returnsDataList)
      })
    },
    //退款周数据
    returnsWeeksList(){
      return orderReturnsDataHandoff(this.SelectedDates, this.SelectedCategories).then(response=>{
        this.returnsData.week = [];
        this.returnsDataList = [];
        this.lineOptionData = [];
        this.returnsDataList = response.rows;
        for (let i = 0; i < this.returnsDataList.length; i++) {
          this.returnsData.week.push(this.returnsDataList[i].returnPrice)
          this.lineOptionData.push(this.returnsDataList[i].weeks);
          this.tableWeek.push(this.lineOptionData[i]);
        }
        console.log("this.ordersList",this.returnsDataList)
      })
    },
    //退款月数据
    returnsMonthsList(){
      return orderReturnsDataHandoff(this.SelectedDates, this.SelectedCategories).then(response=>{
        this.returnsData.month = [];
        this.returnsDataList = [];
        this.lineOptionData = [];
        this.yearData = [];
        this.returnsDataList = response.rows;
        for (let i = 0; i < this.returnsDataList.length; i++) {
          this.returnsData.month.push(this.returnsDataList[i].returnPrice)
          this.yearData.push(this.returnsDataList[i].years)
          this.lineOptionData.push(this.returnsDataList[i].years+"年"+this.returnsDataList[i].months);
        }
        console.log("this.ordersList",this.returnsDataList)
      })
    },
    //退款年数据
    returnsYearsList(){
      return orderReturnsDataHandoff(this.SelectedDates, this.SelectedCategories).then(response=>{
        this.returnsData.year = [];
        this.returnsDataList = [];
        this.lineOptionData = [];
        this.yearData = [];
        this.returnsDataList = response.rows;
        for (let i = 0; i < this.returnsDataList.length; i++) {
          this.returnsData.year.push(this.returnsDataList[i].returnPrice)
          this.lineOptionData.push(this.returnsDataList[i].years);
        }
        console.log("this.ordersList",this.returnsDataList)
      })
    },
    //成交日数据
    orderDealDayList(){
      return orderDealList(this.SelectedDates, this.SelectedCategories).then(response=>{
        this.orderDealDateList = [];
        this.transactionsData.day = [];
        this.lineOptionData = [];
        this.orderDealDateList = response.rows;
        for (let i = 0; i <this.orderDealDateList.length ; i++) {
          this.transactionsData.day.push(this.orderDealDateList[i].orderCount)
          this.lineOptionData.push(this.orderDealDateList[i].orderUpdateTime)
        }
        console.log("this.orderDealDateList数据",this.orderDealDateList)
      })
    },
    //成交周数据
    orderDealWeekList(){
      return orderDealList(this.SelectedDates, this.SelectedCategories).then(response=>{
        this.orderDealDateList = [];
        this.transactionsData.week = [];
        this.lineOptionData = [];
        this.orderDealDateList = response.rows;
        for (let i = 0; i <this.orderDealDateList.length ; i++) {
          this.transactionsData.week.push(this.orderDealDateList[i].orderCount)
          this.lineOptionData.push(this.orderDealDateList[i].years+"年"+this.orderDealDateList[i].weeks)
          this.tableWeek.push(this.lineOptionData[i])
        }
        console.log("this.orderDealDateList数据",this.orderDealDateList)
      })
    },
    //成交月数据
    orderDealMonthList(){
      return orderDealList(this.SelectedDates, this.SelectedCategories).then(response=>{
        this.orderDealDateList = [];
        this.transactionsData.month = [];
        this.lineOptionData = [];
        this.orderDealDateList = response.rows;
        for (let i = 0; i <this.orderDealDateList.length ; i++) {
          this.transactionsData.month.push(this.orderDealDateList[i].orderCount)
          this.lineOptionData.push(this.orderDealDateList[i].years+"年"+this.orderDealDateList[i].months)
          // this.tableWeek.push(this.lineOptionData[i])
        }
        console.log("this.orderDealDateList数据",this.orderDealDateList)
      })
    },
    //成交年数据
    orderDealYearList(){
      return orderDealList(this.SelectedDates, this.SelectedCategories).then(response=>{
        this.orderDealDateList = [];
        this.transactionsData.year = [];
        this.lineOptionData = [];
        this.orderDealDateList = response.rows;
        for (let i = 0; i <this.orderDealDateList.length ; i++) {
          this.transactionsData.year.push(this.orderDealDateList[i].orderCount)
          this.lineOptionData.push(this.orderDealDateList[i].years)
        }
        console.log("this.orderDealDateList数据",this.orderDealDateList)
      })
    },
    initCharts() {
      this.lineChart = echarts.init(this.$refs.lineChart);//折线图数据
      this.barChart = echarts.init(this.$refs.barChart);//柱状图数据
      this.pieChart = echarts.init(this.$refs.pieChart);//饼图数据
      this.funnelChart = echarts.init(this.$refs.funnelChart);
    },
    updateCharts() {
      const data = this[`${this.activeTab}Data`][this.timeRange];
      //折线图数据
      const lineOption = {
        tooltip: {trigger: 'axis'},
        //折线图x轴数据
        xAxis: {type: 'category', data: this.lineOptionData},
        yAxis: {type: 'value'},
        series: [{data, type: 'line'}]
      };
      this.lineChart.setOption(lineOption);

      //柱状图数据
      const barOption = {
        tooltip: {trigger: 'axis'},
        //柱状图X轴数据
        xAxis: {type: 'category', data: this.lineOptionData},
        yAxis: {type: 'value'},
        series: [{data, type: 'bar'}]
      };
      this.barChart.setOption(barOption);
      //饼图数据
      const pieOption = {
        series: [{
          type: 'pie',
          radius: '55%',
          data: [{value: data.reduce((sum, curr) => sum + curr, 0), name: 'Total'}]
        }]
      };
      this.pieChart.setOption(pieOption);

      const funnelOption = {
        series: [{type: 'funnel', data: [{value: data.reduce((sum, curr) => sum + curr, 0), name: 'Total'}]}]
      };
      this.funnelChart.setOption(funnelOption);

      //更新表格数据
      this.tableData = data.map((value, index) => ({date: this.getDate(index), value}));
    },

    //下半表格数据
    getDate(index) {
      const days = this.lineOptionData;
      switch (this.timeRange) {
        case 'day':
          return days[index];
        case 'week':
          return '第' + (this.tableWeek[index] + 1) + "周";
        case 'month':
          return this.lineOptionData[index] + "月";
        case 'year':
          return this.lineOptionData[index] + "年";
        default:
          return '';
      }
    }
  }
};
</script>

<style scoped>
.data-visualization-panel {
  margin: 20px;
}

.chart {
  width: 100%;
  height: 400px;
}
</style>
